 <template>
     <view class="container" v-if="loading">
         <u-loading-page :loading="loading"></u-loading-page>
     </view>

 	<view class="container" v-else>
		<!-- 支付状态 -->
		<view class="status-name" v-if="order.status !== 'after_sale' ">
			<view class="status" v-if=" order.status === 'unpaid' ">等待付款</view>
			<view class="status" v-else-if=" order.status === 'shipped' && order.shipping_method === 'self_pickup' ">待自提</view>
			<view class="status" v-else-if=" order.status === 'shipped' && order.shipping_method === 'mail' ">商家已发货</view>
			<view class="status" v-else-if=" order.status === 'paid' ">等待商家发货</view>
            <view class="status" v-else-if=" order.status === 'completed' ">订单已完成</view>
            <view class="status" v-else-if=" order.status === 'cancelled' ">订单已取消</view>

			<view class="name" v-if=" order.status === 'unpaid' ">
                剩余时间：<uni-countdown :font-size="18" color="#f55726" :show-day="false"
                                        :show-colon="false"
                                        :hour="countdownData.hours"
                                        :minute="countdownData.minutes"
                                        :second="countdownData.seconds" />订单关闭
            </view>
		</view>

        <!-- 售后状态 -->
        <view class="status-name" v-if="order.status == 'after_sale' ">

            <view class="status" v-if=" order.after_sale_status === 'refunding' ">退款申请中</view>
            <view class="status" v-if=" order.after_sale_status === 'refund_fail' ">卖家拒绝退款</view>
            <view class="status" v-if=" order.after_sale_status === 'refunded' ">已退款</view>

            <view class="status" v-if=" order.after_sale_status === 'returning_refunding' ">退货退款申请中</view>
            <view class="status" v-if=" order.after_sale_status === 'return_refund_agree' ">卖家已同意,待寄回</view>
            <view class="status" v-if=" order.after_sale_status === 'return_refund_back' ">已寄回</view>
            <view class="status" v-if=" order.after_sale_status === 'return_refunded' ">已退货退款</view>
            <view class="status" v-if=" order.after_sale_status === 'return_refund_fail' ">卖家拒绝退货退款</view>

            <view class="status" v-if=" order.after_sale_status === 'exchanging' ">换货申请中</view>
            <view class="status" v-if=" order.after_sale_status === 'exchange_agree' ">卖家已同意,待寄回</view>
            <view class="status" v-if=" order.after_sale_status === 'exchange_fail' ">卖家已拒绝换货</view>
            <view class="status" v-if=" order.after_sale_status === 'exchange_back' ">已寄回</view>
            <view class="status" v-if=" order.after_sale_status === 'exchange_shipped' ">换货已发货</view>
            <view class="status" v-if=" order.after_sale_status === 'exchange' ">换货已完成</view>

        </view>


		<!-- 查看售后信息 -->
		<view class="sales-box" v-if=" order.after_sale_status !== 'none' " @tap="goAfterSalesDetail">
			<view>查看售后信息</view>
			<u-icon name="arrow-right" color="#516DDB" size="16"></u-icon>
		</view>

        <!-- 地址信息 -->
 		<view class="item" v-if=" order.shipping_method === 'mail' ">
			<view class="icon">
				<u-image width="100%" height="2rpx" :src="getServerStatic('/static/images/line.png')" ></u-image>
			</view>
 			<view style="width: 100%;">
 				<view class="user-info-box">
 					<view class="user-info">
 						<view class="name">{{ order.shipping_name }}</view>
 						<view class="name">{{ order.shipping_mobile }}</view>
 					</view>
 				</view>
 				<view class="address">
 					{{ order.shipping_address }}
 				</view>
 			</view>
 		</view>

        <view class="item" v-if=" order.shipping_method === 'self_pickup' ">
            <view class="icon">
                <u-image width="100%" height="2rpx" :src="getServerStatic('/static/images/line.png')" ></u-image>
            </view>
            <view style="width: 100%;">
                <view class="user-info-box">
                    <view class="user-info">
                        <view class="name">{{ systemStore.mallPickupAddressName }}</view>
                        <view class="name">{{ systemStore.mallPickupAddressMobile }}</view>
                    </view>
                    <view class="icon-box" style="position: relative;z-index: 99;" @tap="showPickupAddressMap">
                        <view class="">位置导航</view>
                        <u-image width="24rpx" height="24rpx" :src="getServerStatic('/static/images/a19.png')" ></u-image>
                    </view>
                </view>
                <view class="address">
                    {{ systemStore.mallPickupAddress }}
                </view>
            </view>
        </view>


 		<view class="order-item">

 			<view class="commodity-box" v-for="(item, index) in orderProducts" :key="index">
 				<view class="left">
 					<!-- <u-image width="170rpx" height="155rpx" src="/static/logo.png"></u-image> -->
                    <u-image width="170rpx" height="155rpx" :src="checkAndFixUrl(item.product_cover)" mode="aspectFit"></u-image>
 				</view>
 				<view class="right">
 					<view class="com-title">{{ item.product_name }}</view>
 					<view class="sku-box">规格：{{ item.product_sku }}</view>
 					<view class="count-box">购买数量：{{ item.quantity }}件</view>
 				</view>
 			</view>

 			<view class="content-box">
 				<view class="content-item">
 					<text>商品总计</text>
 					<text>￥{{ orderTotals.sub_total }}</text>
 				</view>
 				<view class="content-item">
 					<text>抵扣券</text>
 					<text v-if="orderTotals.coupon_discount > 0">减{{ orderTotals.coupon_discount }}元</text>
 					<text v-else>--</text>
 				</view>
 				<view class="content-item">
 					<text>配送方式</text>
 					<text v-if=" order.shipping_method === 'self_pickup' ">到店自提</text>
 					<text v-else>快递邮寄</text>
 				</view>
				<view class="content-item">
					<text>运费</text>
					<text v-if="orderTotals.shipping > 0">￥{{ orderTotals.shipping }}</text>
					<text v-else>--</text>
				</view>
 			</view>

			<view class="all-price-box">
				<view class="">合计</view>
				<view class="price">￥{{ orderTotals.order_total }}</view>
			</view>
 		</view>

		<!-- 订单信息 -->
		<view class="order-item">
			<view class="status-box">
				<view class="name">订单信息</view>
			</view>
			<view class="content-box">
				<view class="content-item">
					<text>订单编号</text>
					<view class="">
						<text>{{ order.number }}</text>
						<text class="copy" @tap="handleCloneClick(order.number)">复制</text>
					</view>
				</view>
				<view class="content-item">
					<text>下单时间</text>
					<text>{{ order.created_at }}</text>
				</view>
				<view class="content-item">
					<text>支付方式</text>
					<text v-if=" order.payment_method_code === 'wechat' ">微信支付</text>
					<text v-if=" order.payment_method_code === 'balance' ">余额支付</text>
				</view>
				<view class="content-item">
					<text>付款时间</text>
					<text v-if="order?.payment_time">{{ order.payment_time }}</text>
					<text v-else>--</text>
				</view>
				<view class="content-item">
					<text>发货时间</text>
					<text v-if="order?.shipping_time">{{ order.shipping_time }}</text>
					<text v-else>--</text>
				</view>
				<view class="content-item">
					<text>收货时间</text>
					<text v-if="order?.delivery_time">{{ order.delivery_time }}</text>
                    <text v-else>--</text>
                </view>
			</view>
		</view>

 		<!-- 物流单号 -->
 		<view class="order-item" v-if=" order.shipping_method === 'mail' && order.logistic_number !== '' ">
 			<view class="status-box">
 				<view class="name">物流单号</view>
 			</view>
 			<view class="content-box">
 				<view class="content-item">
 					<text>物流单号：</text>
 					<view class="order-no">
 						<text>{{ order.logistic_number }}</text>
						<u-image width="26rpx" height="26rpx" :src="getServerStatic('/static/images/a62.png')" @tap="handleCloneClick(order.logistic_number)"></u-image>
 					</view>
 				</view>
 				<view class="content-img" v-if=" order.logistic_photo !== '' ">
 					<u-image radius="10" mode="aspectFit" width="100%" height="220rpx" :src="checkAndFixUrl(order.logistic_photo)"></u-image>
 				</view>
 			</view>
 		</view>

		<!-- 退款信息 -->
		<view class="order-item" v-if=" order.status === 'cancelled' && order.refund_no !== '' ">
			<view class="status-box">
				<view class="name">退款信息</view>
			</view>
			<view class="content-box">
				<view class="content-item">
					<text>退款原因</text>
					<text>{{ order.cancel_reason }}</text>
				</view>
				<view class="content-item">
					<text>申请时间</text>
					<text>{{ order.refund_at }}</text>
				</view>
				<view class="content-item">
					<text>退款到账时间</text>
					<text>{{ order.refund_at }}</text>
				</view>
			</view>
		</view>


		<!-- 联系商家 -->
		<view class="concat-card" @tap="showMallMobile = true">
			<u-image width="24rpx" height="32rpx" :src="getServerStatic('/static/images/a58.png')" ></u-image>
			<view class="">联系商家</view>
		</view>
 	</view>

 	<!-- 待支付 按钮区 -->
 	<view class="btn" v-if=" order.status === 'unpaid' ">
        <view class="">
            <u-button plain throttleTime="1000"
                      :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                      :hairline="true" type="mini" shape="circle"
                      color="#516DDB"
                      @click="showCancelPop">取消订单</u-button>
        </view>

        <view class="">
            <u-button throttleTime="1000"
                      :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                      :hairline="false" type="mini" shape="circle"
                color="#516DDB" @click="showPayPop">去支付</u-button>
        </view>
 	</view>

     <!-- 待发货 按钮区 -->
     <view class="btn" v-else-if=" order.status === 'paid' ">
         <view class="">
             <u-button plain throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="true" type="mini" shape="circle"
                       color="#516DDB"
                       @click="showCancelPop">取消订单</u-button>
         </view>
     </view>

     <!-- 物流已发货 按钮区 -->
     <view class="btn" v-else-if=" order.status === 'shipped' && order.shipping_method === 'mail' ">
         <view class="">
             <u-button plain throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="true" type="mini" shape="circle"
                       color="#516DDB" @click="showSalesPop">申请售后</u-button>
         </view>

         <view class="">
             <u-button throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="false" type="mini" shape="circle"
                 color="#516DDB" @click="handleConfirmReceipt">确认收货</u-button>
         </view>
     </view>

     <!-- 自提已发货 按钮区 -->
     <view class="btn" v-else-if=" order.status === 'shipped' && order.shipping_method === 'self_pickup' ">
<!--         <view class="">-->
<!--             <u-button plain throttleTime="1000"-->
<!--                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"-->
<!--                       :hairline="true" type="mini" shape="circle"-->
<!--                       color="#516DDB"-->
<!--                       @click="showCancelPop">取消订单</u-button>-->
<!--         </view>-->

         <view class="">
             <u-button throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="false" type="mini" shape="circle"
                       color="#516DDB" @click="handleConfirmReceipt">确认收货</u-button>
         </view>
     </view>

     <!-- 售后中 换货已发货 按钮区 -->
     <view class="btn" v-else-if=" order.status === 'after_sale' && order.after_sale_status === 'exchange_shipped' ">

         <view class="">
             <u-button throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="false" type="mini" shape="circle"
                       color="#516DDB" @click="handleConfirmReceipt">确认收货</u-button>
         </view>

     </view>

     <!-- 订单完成或取消 按钮区 -->
     <view class="btn" v-else-if=" order.status === 'completed' || order.shipping_method === 'cancelled' ">
         <!-- 再次购买 -->
         <view class="">
             <u-button throttleTime="1000"
                       :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}"
                       :hairline="false" type="mini" shape="circle"
                 color="#516DDB" @click="handlePurchaseAgain">再次购买</u-button>
         </view>

         <!-- 待评价 -->
        <view class="" v-if=" order.reviewed === 1 ">
            <u-button throttleTime="1000" :customStyle="{width: '216rpx', height: '86rpx', letterSpacing: '.1rem'}" :hairline="false" type="mini" shape="circle"
                color="#516DDB" @click="goEvaluate">去评价</u-button>
        </view>
     </view>

     <!-- 申请售后 -->
     <!--		<view class="">-->
     <!--			<u-button plain throttleTime="1000" :customStyle="{width: '298rpx', height: '86rpx', letterSpacing: '.1rem'}" :hairline="true" type="mini" shape="circle"-->
     <!--				color="#516DDB" @click="showApplyRefundPop">申请退货退款</u-button>-->
     <!--		</view>-->

	<!-- 取消订单弹窗 -->
	<u-popup closeable bgColor="transparent" :show="cancelPop" @close="cancelPop = false">
		<view class="cancel-pop">
			<view class="pop-title">请选择取消订单的原因（必选）：</view>
			<view class="radio-wrap">
				<u-radio-group v-model="radioValue" placement="column">
					<u-radio  :customStyle="{marginBottom: '46rpx'}" v-for="(item, index) in radioList" :key="index" activeColor="#6087EF"
						:label="item.name" :name="item.name">
					</u-radio>
				</u-radio-group>
			</view>
			<view class=" ">
				<u-button throttleTime="1000" :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}"
                          :hairline="false"
                          type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                          @tap="toCancel"
                >确认</u-button>
			</view>
		</view>
	</u-popup>


	<!-- 支付弹窗 -->
	<u-popup closeable bgColor="transparent" :show="payPop" @close="payPop = false">
		<view class="pay-pop">
			<view class="pay-content">
				<view class="title">
					选择支付方式
				</view>
				<!-- 支付选择 -->
				<view class="payment-select-box">
					<u-radio-group v-model="paymentWay" placement="column" @change="handlePaymentWayChange">
						<view class="payment-item" @click="handleSelectPayment('wechat')">
							<view class="left">
								<u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a40.png')" ></u-image>
								<view class="pay-name">微信支付</view>
							</view>
							<view class="right">
								<u-radio activeColor="#516DDB" name="wechat"></u-radio>
							</view>
						</view>
						<view class="payment-item center" @click="handleSelectPayment('balance')">
							<view class="left">
								<u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a41.png')"></u-image>
								<view class="pay-name">余额支付</view>
								<view class="pay-tip">当前余额：{{ userStore.store_balance }}元</view>
							</view>
							<view class="right">
								<u-radio activeColor="#516DDB" name="balance" :disabled="orderTotals.order_total > userStore.store_balance"></u-radio>
							</view>
						</view>
					</u-radio-group>
				</view>
			</view>
			<view class="pay-btn">
				<u-button throttleTime="1000" :customStyle="{height: '86rpx', letterSpacing: '.1rem', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)'}" :hairline="false" type="mini"
					shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @tap="payConfirm" >确认</u-button>
			</view>
		</view>
	</u-popup>

	<!-- 售后申请弹窗 -->
	<u-popup closeable bgColor="transparent" :show="salesPop" @close="salesPop = false">
		<view class="sales-pop">
			<view class="sales-content">
				<view class="title">
					请选择售后申请
				</view>
				<view :class="['sales-item', salesCurrent === item.type ? 'active' : '']" v-for="(item, i) in salesList" :key="item.id" @tap="salesCurrentChange(item.type)">
					<view class="left">
						<u-image width="100rpx" height="100rpx" :src="getServerStatic(item.href)"></u-image>
					</view>
					<view class="right">
						<view class="name">{{item.name}}</view>
						<view class="sub-name">{{item.subName}}</view>
					</view>
				</view>
			</view>

			<view class="pay-btn">
				<u-button throttleTime="1000" :customStyle="{height: '86rpx', letterSpacing: '.1rem', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)'}" :hairline="false" type="mini"
					shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @click="handleApplyAfterSales">确认</u-button>
			</view>
		</view>
	</u-popup>

     <!-- 寄回订单号 -->
     <u-popup closeable bgColor="transparent" :show="canReturnLogistics" @close="canReturnLogistics = false">
         <view class="return-logistics-pop">
             <view class="sales-content">
                 <view class="title">
                     卖家已同意售后申请
                 </view>
                 <view class="status-box default">
                     <view class="name">寄回运单号</view>
                     <view class="">
                         <u--input inputAlign="center"
                                   placeholder="请输入运单号"
                                   v-model="rmaLogisticNumber"
                                   border="none">
                         </u--input>
                     </view>
                 </view>
                 <view class="content-box">
                     <view class="upload-box">
                         <u-upload
                           :fileList="rmaLogisticPhoto"
                           @afterRead="afterReadLogisticPhoto"
                           @delete="deletePicLogisticPhoto"
                           :multiple="false"
                           :maxCount="1"
                           :previewFullImage="true"
                         >
                             <u-image width="200rpx" height="200rpx" :src="getServerStatic('/static/images/upload.png')"></u-image>
                         </u-upload>
                     </view>
                 </view>
             </view>

             <view class="pay-btn">
                 <u-button throttleTime="1000" :customStyle="{height: '86rpx', letterSpacing: '.1rem', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)'}" :hairline="false" type="mini"
                           shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                           @tap="handleReturnLogistics"
                 >确认</u-button>
             </view>
         </view>
     </u-popup>




	<!-- 申请退货退款 -->
	<u-modal showCancelButton :show="applyRefundPop" title="申请退货退款" @cancel="applyRefundPop = false" @confirm="applyRefundPop = false" confirmColor="#516DDB">
		<view class="tip">是否要确定申请退货退款？</view>
	</u-modal>

     <!-- 客服电话 -->
     <u-action-sheet round="30rpx" :show="showMallMobile" :actions="mallMobileActions" title="" description="" @close="showMallMobile = false"
                     @select="callMallMobileConfirm">
     </u-action-sheet>

 </template>

 <script setup>
    import {ref} from "vue"
    import {onLoad, onShow, onPullDownRefresh} from '@dcloudio/uni-app'
    import {cancellationMallOrder, confirmMallDelivery, getMallOrderInfo, initiateMallPayment} from "@/api/mall";
    import {useSystemStore, useUserStore} from "@/store";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    import useUniAPi from "@/hooks/useUniAPi";
    import {getUploadToken, uploadImage} from "@/api/upload";
    import {returnMallLogistics} from "@/api/rma";
    const { navigateTo, redirectTo, payment } = useUniAPi()
    // 系统
    const systemStore = useSystemStore()
    // 用户store
    const userStore = useUserStore();

    // 支付方式
    const paymentWay = ref('wechat')
    const handlePaymentWayChange = (e) => {
        paymentWay.value = '' + e;
    }

    const handleSelectPayment = (way) => {
        paymentWay.value = way;
    }

    // 复制
    const handleCloneClick = (cloneText) => {
        uni.setClipboardData({
            data: cloneText,
            success: () => {
                uni.showToast({
                    title: '复制成功'
                })
            }
        })
    }

    // 点击再次购买
    const handlePurchaseAgain = () => {
        redirectTo({
            url: "/pages/home/home"
        })
    }

    const payConfirm = async () => {
        payPop.value = false

        uni.showLoading({
            title: '加载中'
        });
        const {code ,data, message} = await initiateMallPayment({orderId: orderId.value, method: paymentWay.value})
        uni.hideLoading();

        if (code === 1) {
            if (paymentWay.value === 'wechat') {
                const result =  await payment(data)
                if (result?.errMsg && result.errMsg === 'requestPayment:ok') {
                    uni.showToast({
                        mask: true,
                        title: '支付完成!',
                        icon: 'success'
                    })
                    await handleGetOrderInfo()
                } else {
                    uni.showToast({
                        mask: true,
                        title: '取消支付!',
                        icon: 'none'
                    })
                }
            } else {
                uni.showToast({
                    mask: true,
                    title: '支付完成!',
                    icon: 'success'
                })
                userStore.syncUserInfo()
                await handleGetOrderInfo()
            }
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                }
            });
        }
    }

     const showPickupAddressMap = () => {
         uni.openLocation({
             latitude: Number(systemStore.mallPickupAddressLatitude),
             longitude: Number(systemStore.mallPickupAddressLongitude),
             name: systemStore.mallPickupAddressName,
             address: systemStore.mallPickupAddress,
             scale: 18,
             success: function () {
                 console.log('success');
             },
             fail: function (err) {
                 console.log(err);
             }
         });
     }


     const order = ref({})
     const orderProducts = ref([])
     const orderTotals = ref({})
     const orderId = ref(0)

     const loading = ref(true)
     onLoad((evt) => {
         if (!evt?.order_id) {
             goBack()
         }
         orderId.value = evt?.order_id || 0

         handleGetOrderInfo()
        // uni.setNavigationBarTitle({
        //     title: status == 1 ? '待支付订单' : '订单详情'
        // })
    })

    onPullDownRefresh(() => {
        handleGetOrderInfo()
    })

    onShow(() => {
        handleGetOrderInfo()
    })

    // 倒计时
    const countdownData = reactive({
        hours: 0,
        minutes: 0,
        seconds: 0
    })
    // 获取订单详情.
    const handleGetOrderInfo = async () => {
        loading.value = true
        // uni.showLoading({
        //     title: '加载中'
        // });
        const {code, data, message } = await getMallOrderInfo({orderId: orderId.value})
        // uni.hideLoading();
        if (code === 1) {
            order.value = data
            orderProducts.value = data?.order_products ?? []
            let orderTotalArr = data?.order_totals ?? []
            // 转为订单
            orderTotals.value = orderTotalArr.reduce((acc, item) => {
                const key = item.code;
                acc[key] = parseFloat(item.value);
                return acc;
            }, {});
            // 倒计时
            if (data.status === 'unpaid') {
                // 计算剩余时间
                const endTime = new Date(data.payment_end_time).getTime();
                const currentTime = new Date().getTime();
                const timeDifference = Math.max(0, endTime - currentTime); // 确保剩余时间不为负数

                countdownData.seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
                countdownData.minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
                countdownData.hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            }
            loading.value = false

            // 寄回
            handleCanReturnLogistics()
        } else {
            loading.value = false

            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        goBack()
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
        loading.value = false
    }

    const cancelPop = ref(false)
    const payPop = ref(false)
    const salesPop = ref(false)
    const applyRefundPop = ref(false)

    // 单选
    const radioValue = ref('')
    const radioList = ref([{
            name: '不想要了',
        },
        {
            name: '选错/多选',
        },
        {
            name: '收件人人填错了',
        },
        {
            name: '商品选错了',
        },
        {
            name: '有更便宜的了，不想要了/其他原因',
        },
    ])

    // 取消订单.
    const toCancel = async () => {
        console.log(radioValue.value)
        if (!radioValue.value) {
            uni.showToast({
                mask: true,
                title: '请选择原因!',
                icon: 'error'
            })
            return
        }

        cancelPop.value = false
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await cancellationMallOrder({orderId: orderId.value, cancelReason: radioValue.value})
        uni.hideLoading();

        if (code == 1) {
            uni.showToast({
                mask: true,
                title: '取消完成',
                icon: 'success'
            })
            userStore.syncUserInfo()
            await handleGetOrderInfo()
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                }
            });
        }
    }

    // 确认收货
    const handleConfirmReceipt = () => {
        console.log('确认收货')
        uni.showModal({
            title: '提示',
            content: "确认收货?",
            showCancel: true,
            success: function (res) {
                if (res.confirm) {
                    const toReceipt = async () => {
                        uni.showLoading({
                            title: '加载中'
                        });
                        const {code, data, message} = await confirmMallDelivery({orderId: orderId.value})
                        uni.hideLoading();

                        if (code === 1) {
                            await handleGetOrderInfo()
                        } else {
                            uni.showModal({
                                title: '提示',
                                content: message ?? "请求异常",
                                showCancel: false,
                                success: function (res) {
                                }
                            });
                        }
                    }
                    toReceipt()
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    }

    const salesCurrent = ref('return_and_refund')
    const rmaReason = ref('')
    const rmaImages = ref('')

    const chooseRmaImage = () => {

    }

    // 售后类型
    const salesList = ref([
        {
            name: '我要退货退款',
            id: 0,
            subName: '我已收到货，需要退还收到的货物',
            type: 'return_and_refund',
            href: '/static/images/a59.png'
        },
        {
            name: '我要退款（无需退货）',
            id: 1,
            type: 'refund_do_not_return',
            subName: '未收到货，或与商家协商后申请',
            href: '/static/images/a60.png'
        },
        {
            name: '我要换货',
            id: 2,
            type: 'exchange',
            subName: '对收到的商品不满意，与商家协商换货',
            href: '/static/images/a61.png'
        },
    ])
    // 切换
    const salesCurrentChange = index => {
        salesCurrent.value = index
    }

    // 申请售后
    const handleApplyAfterSales = () => {
        salesPop.value = false
        uni.navigateTo({
            url: `/mine/commodity/rma-apply?order_id=${orderId.value}&rma_type=${salesCurrent.value}`
        })
    }

    const rmaLogisticNumber = ref('')
    const canReturnLogistics = ref(false)

    const rmaLogisticPhoto = ref([])
    const afterReadLogisticPhoto = async (event) => {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        rmaLogisticPhoto.value.push({
            ...event.file,
            status: 'uploading',
            message: '上传中'
        })
        console.log(event)

        const {code, data, message} = await getUploadToken()
        if (code !== 1) {
            uni.showModal({
                title: '提示',
                content: message ?? "获取上传token异常",
                showCancel: false,
                success: function (res) {
                }
            });
            return
        }

        const uploadRes = await uploadImage({file: event.file.url}, data.token)
        const uploadResData = JSON.parse(uploadRes)
        if (uploadResData.code === 1) {
            rmaLogisticPhoto.value.splice(event.index,1, Object.assign(event.file, {
                status: 'success',
                message: '',
                url: uploadResData.data.url,
                path: uploadResData.data.path
            }))
        }
        console.log(uploadResData)
    }
    const deletePicLogisticPhoto = (event) => {
        console.log(event)
        rmaLogisticPhoto.value.splice(event.index, 1)
        console.log(rmaLogisticPhoto.value)
    }

    // 填写退换物流信息
    const handleReturnLogistics = async () => {
        if (!rmaLogisticNumber.value) {
            uni.showToast({
                mask: true,
                title: '请填写物流单号!',
                icon: 'none'
            })
            return
        }
        canReturnLogistics.value = false
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await returnMallLogistics({orderId: orderId.value, rmaLogisticNumber: rmaLogisticNumber.value, rmaLogisticPhoto: rmaLogisticPhoto?.value[0]?.path ?? ''})
        uni.hideLoading();

        if (code === 1) {
            uni.showModal({
                title: '提示',
                content: "提交成功",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        handleGetOrderInfo()
                    }
                }
            });
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                }
            });
        }
    }

    // 可以填写寄回订单号
    const handleCanReturnLogistics = () => {
        let status = order.value.status ?? ''
        let after_sale_status = order.value.after_sale_status ?? ''
        if (
          status == 'after_sale' && (
            after_sale_status == 'return_refund_agree' ||
            after_sale_status == 'exchange_agree'
            )
        ) {
            canReturnLogistics.value = true
            return true
        } else {
            canReturnLogistics.value = false
            return false
        }
    }

    // 申请退货退款弹窗
    const showApplyRefundPop = () => {
        applyRefundPop.value = true
    }
    // 三个弹窗显示
    const showCancelPop = () => {
        cancelPop.value = true
    }
    const showPayPop = () => {
        payPop.value = true
    }
    const showSalesPop = () => {
        salesPop.value = true
    }
    const goAddressList = () => {
        uni.navigateTo({
            url: '/mine/address/list?name=1'
        })
    }
    // 跳转售后详情
    const goAfterSalesDetail = () => {
        uni.navigateTo({
            url: `/mine/commodity/after-sales-detail?order_id=${orderId.value}&order_status=${order.value.status}&after_sale_status=${order.value.after_sale_status}`
        })
    }
    // 跳转去评价
    const goEvaluate = () => {
        uni.navigateTo({
            url: `/mine/commodity/evaluate?order_id=${orderId.value}`
        })
    }

    // 客服
    const showMallMobile = ref(false)
    const mallMobileActions = ref([{
            name: `一键拨打：${systemStore.mallCustomerMobile}`,
            isCall: true
        },
        {
            name: '取消',
            isCall: false
        },
    ])

    const callMallMobileConfirm = (e) => {
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.mallCustomerMobile
            })
        }
    }

    const goBack = () => {
        uni.navigateBack()
    }
 </script>

 <style lang="scss" scoped>
 	.container {
 		padding: 60rpx 26rpx 200rpx;
 	}

	.sales-box {
		padding: 28rpx 0;
		background: #FFFFFF;
		border-radius: 20rpx;
		margin: 28rpx 0 30rpx;
		font-size: 32rpx;
		color: #516DDB;
		@include center();
		& > view {
			font-size: 32rpx;
			margin-right: 8rpx;
		}
	}
	.status-name {
		color: #F55726;
		font-weight: bold;
		.status {
			font-size: 32rpx;
		}
		.name {
			margin: 17rpx 0 28rpx;
			font-size: 28rpx;
            display: flex;
            align-items: center;
		}
	}

 	.icon-box {
 		display: flex;
 		align-items: center;

 		&>view {
 			margin-right: 10rpx;
 			color: #516DDB;
			font-size: 28rpx;
 		}
 	}

 	.item {
		position: relative;
 		@include between(100%);
 		margin-bottom: 40rpx;
 		padding: 34rpx 38rpx;
 		background: #FFFFFF;
 		border-radius: 20rpx 20rpx 0 0;
		.icon {
			width: 100%;
			position: absolute;
			left: 0;
			bottom: 0;
			z-index: 3;
		}
		.user-info-box {
			@include between(100%);
			.user-info {
				@include start();
				.name {
					font-size: 28rpx;
					font-weight: bold;
					color: #000000;
					margin-right: 26rpx;
				}
			}
		}

 		.address {
 			margin-top: 24rpx;
 			font-size: 28rpx;
 			color: #000000;
 		}
 	}

 	.order-item {
 		margin-bottom: 30rpx;
 		padding: 38rpx 38rpx 1rpx;
 		background: #FFFFFF;
 		border-radius: 30rpx;

 		.address-box {
 			@include between(100%);
 			color: #000000;
 			font-size: 26rpx;
 			margin-bottom: 12rpx;

 		}

 		.last {
 			margin-top: 12rpx;
 		}

 		.status-box {
            @include between(100%);
 			padding-bottom: 32rpx;
 			border-bottom: 1rpx solid #E8E8E8;
 			margin-bottom: 30rpx;

 			.name {
 				font-size: 30rpx;
 				font-weight: bold;
 				color: #000000;
 			}
            .tip {
                color: #999999;
            }
 			.status {
 				color: #D66A44;
 			}

 			.status1 {
 				color: #AAAAAA;
 			}
 		}
        .default {
            padding-bottom: 0;
            border-bottom: none;
            // justify-content: flex-start;
            .name {
                margin-right: 36rpx;
            }
        }
		.commodity-box {
			@include between(100%, 100%);
			margin-bottom: 28rpx;
			padding-bottom: 40rpx;
			border-bottom: 1rpx solid #F5F5F5;
			.right {
				flex: 1;
				margin-left: 22rpx;
				@include between(100%, 170rpx);
				flex-direction: column;
				align-items: flex-start;
				padding: 10rpx 0;
				color: #000000;
				font-size: 30rpx;
				.com-title {
					@include over-ellip(450rpx);
					font-weight: bold;
				}
                .sku-box {
                    @include over-ellip(450rpx);
                }
			}
		}

 		.content-box {
 			width: 100%;
 			position: relative;
 			font-size: 26rpx;
 			color: #606672;

 			.content-item {
 				@include between(100%);
 				margin-bottom: 30rpx;
 				font-size: 28rpx;
 				color: #000000;
				.order-no {
					@include start();
					& > text {
						color: #312C2A;
						margin-right: 20rpx;
					}

				}

 				&>text {
 					&:nth-child(2) {
 						color: #312C2A;
 					}
 				}
				.copy {
					display: inline-block;
					margin-left: 22rpx;
					color: #516DDB;
					font-size: 30rpx;
				}
 			}

 			.icon {
 				position: absolute;
 				bottom: 0;
 				right: 0;
 				z-index: 99;
 			}
 		}

		.all-price-box {
			@include between(100%);
			font-size: 28rpx;
			color: #000000;
			padding-top: 26rpx;
			padding-bottom: 30rpx;
			border-top: 1rpx solid #f5f5f5;
			.price {
				font-size: 34rpx;
				color: #F55726;
			}
		}

 		.btns-box {
 			padding-top: 32rpx;
 			border-top: 1rpx solid #E8E8E8;
 			margin-top: 30rpx;
 			@include between(100%);

 			.message {
 				font-size: 26rpx;
 				color: #D66A44;
 			}
 		}
 	}

	.concat-card {
		margin-top: 40rpx;
		margin-bottom: 40rpx;
		padding: 28rpx 0;
		background: #FFFFFF;
		border-radius: 20rpx;
		font-size: 32rpx;
		color: #516DDB;
		@include center(100%);
		& > view {
			margin-left: 10rpx;
		}
	}


 	.btn {
		padding-top: 26rpx;
		padding-right: 30rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
 		position: fixed;
		left: 0;
 		bottom: 0;
 		z-index: 999;
		@include end(100%);
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);
		& > view {
			margin-left: 18rpx;

		}
 	}

	.pay-pop {
		width: 100%;
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		.pay-content {
			padding: 43rpx 40rpx 0;
		}
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #000000;
			margin-bottom: 60rpx;
		}
		.payment-select-box {
			.payment-item {
				@include between(100%);
				.left {
					@include start();
					.pay-name {
						color: #000000;
						font-size: 28rpx;
						margin-left: 16rpx;
					}
					.pay-tip {
						margin-left: 16rpx;
						color: #B3BCCC;
					}
				}
			}
			.center {
				margin: 50rpx 0 78rpx;
			}
		}
		.pay-btn {
			padding: 13rpx 55rpx 23rpx;
			box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);

		}
	}

	.cancel-pop {
		padding: 40rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153, 153, 153, 0.16);
		border-radius: 30rpx 30rpx 0rpx 0rpx;

		.pop-title {
			color: #000000;
			font-size: 32rpx;
			font-weight: bold;
		}

		.info {
			margin-top: 14rpx;
			margin-bottom: 40rpx;
			background: #F6F6F6;
			border-radius: 20rpx;
			padding: 26rpx 30rpx;
			color: #000000;

			&>view {
				margin-bottom: 16rpx;
			}
		}
		.radio-wrap {
			margin-top: 36rpx;
		}
		.cancel-btn {
			// box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);
			margin-top: 50rpx;
		}
	}

    .return-logistics-pop {
        background: #F5F6F8;
        box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153,153,153,0.16);
        border-radius: 30rpx 30rpx 0rpx 0rpx;
        .sales-content {
            padding: 43rpx 40rpx;
        }
        .status-box {
            height: 200rpx;
            display: flex;
            align-items: center;
            padding-bottom: 32rpx;
            border-bottom: 1rpx solid #E8E8E8;
            margin-bottom: 30rpx;
        }
        .content-box {
            width: 100%;
            position: relative;
            font-size: 26rpx;
            color: #606672;
            .upload-box {
                margin-top: 30rpx;
                padding-bottom: 30rpx;
                .image-box {
                    display: flex;
                }
            }
        }
        .default {
            padding-bottom: 0;
            border-bottom: none;
            // justify-content: flex-start;
            .name {
                margin-right: 36rpx;
            }
        }
        .pay-btn {
            background: #FFFFFF;
            padding: 15rpx 55rpx 23rpx;
            box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);

        }
    }

	.sales-pop {
		background: #F5F6F8;
		box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153,153,153,0.16);
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		.sales-content {
			padding: 43rpx 40rpx;
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #000000;
				margin-bottom: 62rpx;
			}
			.sales-item {
				border: 2rpx solid #FFFFFF;
				@include start(100%);
				background: #FFFFFF;
				border-radius: 30rpx;
				padding: 40rpx 30rpx;
				margin-bottom: 40rpx;
				.right {
					margin-left: 20rpx;
					@include between(100%, 100rpx);
					align-items: flex-start;
					flex-direction: column;
					.name {
						font-size: 32rpx;
						color: #000000;
					}
					.sub-name {
						color: #999999;
						font-size: 28rpx;
					}
				}
			}
			.active {
				border: 2rpx solid #516DDB;
			}
		}
		.pay-btn {
			background: #FFFFFF;
			padding: 15rpx 55rpx 23rpx;
			box-shadow: 0rpx 0rpx 16rpx 1rpx rgba(0,0,0,0.1);

		}
	}
 </style>
